package com.example.androidthreadtest;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

/**
 * TODO: 增加了Android handler字体切换线程demo
 *
 * @author MAC
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static final int UPDATE_TEXT = 1;
    public static final int UPDATE_TEXT2 = 2;

    private TextView text;

    private Button changeText;
    private Button changeText2;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_TEXT:
                    text.setText("Nice to meet you mac");
                    break;

                case UPDATE_TEXT2:
                    text.setText("Hello mac Wust!");
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        changeText.setOnClickListener(this);
        changeText2.setOnClickListener(this);
    }

    public void initView() {
        text = (TextView) findViewById(R.id.text);
        changeText = (Button) findViewById(R.id.change_text);
        changeText2 = (Button) findViewById(R.id.change_text2);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.change_text:
                new Thread(() -> {
                    Message message = new Message();
                    message.what = UPDATE_TEXT;
                    handler.sendMessage(message);
                }).start();
                break;

            case R.id.change_text2:
                new Thread(() -> {
                    Message message = new Message();
                    message.what = UPDATE_TEXT2;
                    handler.sendMessage(message);
                }).start();
                break;

            default:
                break;
        }
    }
}